package com.moshang.blog.service.impl;

import com.moshang.blog.core.constant.Constants;
import com.moshang.blog.entity.QETag;
import com.moshang.blog.entity.Rescource;
import com.moshang.blog.entity.SysDict;
import com.moshang.blog.entity.UploadInfo;
import com.moshang.blog.core.utils.MyException;
import com.moshang.blog.service.SysDictService;
import com.moshang.blog.service.SysRescourceService;
import com.moshang.blog.service.UploadInfoService;
import com.moshang.blog.service.UploadService;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.xiaoleilu.hutool.util.RandomUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.security.NoSuchAlgorithmException;

/**
 * @program: blog
 * @description: 七牛云上传
 * @author: xieweiwei
 * @create: 2018-09-30 16:40
 **/
@Service("qiniuService")
public class qiniuServiceImpl implements UploadService {

    @Autowired
    private UploadInfoService uploadInfoService;

    @Autowired
    private SysRescourceService rescourceService;
    @Autowired
    private SysDictService sysDictService;

    private UploadInfo getUploadInfo(){
        return uploadInfoService.getOneInfo();
    }

    private UploadManager getUploadManager(){
        Zone z = Zone.zone0();
        Configuration config = new Configuration(z);
        return new UploadManager(config);
    }

    private BucketManager getBucketManager(){
        Zone z = Zone.zone0();
        Configuration config = new Configuration(z);
        Auth auth = Auth.create(getUploadInfo().getQiniuAccessKey(), getUploadInfo().getQiniuSecretKey());
        return new BucketManager(auth,config);
    }

    private String getAuth(){
        if(getUploadInfo() == null){
            throw new MyException("上传信息配置不存在");
        }
        Auth auth = Auth.create(getUploadInfo().getQiniuAccessKey(), getUploadInfo().getQiniuSecretKey());
        return auth.uploadToken(getUploadInfo().getQiniuBucketName());
    }

    @Override
    public String upload(MultipartFile file, Integer status) throws IOException, NoSuchAlgorithmException {
        String fileName = "", extName = "", filePath = "";
        StringBuffer key = new StringBuffer();
        StringBuffer returnUrl = new StringBuffer(getUploadInfo().getQiniuBasePath());
        if (null != file && !file.isEmpty()) {
            extName = file.getOriginalFilename().substring(
                    file.getOriginalFilename().lastIndexOf("."));
            fileName = RandomUtil.randomUUID() + extName;
            byte[] data = file.getBytes();
            QETag tag = new QETag();
            String hash = tag.calcETag(file);
            String source="qiniu";
            Rescource rescource = rescourceService.selectByCondition(hash,source);
            if( rescource!= null){
                return rescource.getWebUrl();
            }
            String qiniuDir = getUploadInfo().getQiniuDir();

            if(StringUtils.isNotBlank(qiniuDir)){
                key.append(qiniuDir).append("/");
                returnUrl.append(qiniuDir).append("/");
            }
            key.append(fileName);
            returnUrl.append(fileName);
            Response r = getUploadManager().put(data, key.toString(), getAuth());
            if (r.isOK()) {
                filePath = getUploadInfo().getQiniuBasePath() + fileName;
                rescource = new Rescource();
                rescource.setFileName(fileName);
                rescource.setFileSize(new java.text.DecimalFormat("#.##").format(file.getSize()/1024)+"kb");
                rescource.setHash(hash);
                rescource.setFileType(StringUtils.isBlank(extName)?"unknown":extName);
                rescource.setWebUrl(returnUrl.toString());
                rescource.setSource("qiniu");
                if (status==0) {
                    SysDict sysDict = sysDictService.selectByCondition("文件分类", Constants.DEFAULT_CATEGORY);
                    if (sysDict!=null){
                        rescource.setCategory(sysDict.getId());
                    }
                }
                rescourceService.insertRescource(rescource);
            }
        }
        return returnUrl.toString();
    }

    @Override
    public Boolean testAccess(UploadInfo uploadInfo) {
        ClassPathResource classPathResource = new ClassPathResource("static/images/userface1.jpg");
        try {
            Auth auth = Auth.create(uploadInfo.getQiniuAccessKey(), uploadInfo.getQiniuSecretKey());
            String authstr =  auth.uploadToken(uploadInfo.getQiniuBucketName());
            InputStream inputStream = classPathResource .getInputStream();
            Response response = getUploadManager().put(inputStream,"test.jpg",authstr,null,null);
            if(response.isOK()){
                return true;
            }else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public void download(String fileName, String remoteName)throws IOException {

    }
}
